package net.zjitc.list.arrays;

public class MyArrayList<T> implements MyList<T> {
    private Object[] arr = new Object[10];
    private int size = 0;

    /**
     * 添加
     *
     * @param data 值
     * @return
     */
    @Override
    public boolean add(Object data) {
        //如果数组空间不够怎么办？扩容
        container();
        arr[size++] = data;
        return true;
    }

    /**
     * 添加
     *
     * @param index 索引
     * @param data  值
     * @return
     */
    @Override
    public boolean add(int index, Object data) {

        InsertElementPosition(index);
        //空间不够怎么办？
        container();
        //如何插入一个元素
        for (int i = size; i < index; i--) {
            arr[i] = arr[i - 1];
        }
        arr[index] = data;
        size++;

        return true;
    }

    /**
     * 删除
     *
     * @param data 值
     * @return
     */
    @Override
    public T remove(Object data) {
        T oldData = null;
        for (int i = 0; i < size; i++) {
            if (data == arr[i] || data.equals(arr[i])) {
                oldData = (T) arr[i];
                for (int j = 0; j < size - 1; j++) {
                    arr[j] = arr[j + 1];
                }
                break;
            }
        }
        size--;
        return oldData;
    }

    /**
     * 删除
     *
     * @param index 索引
     * @return
     */
    @Override
    public T remove(int index) {
        checkElementPosition(index);
        T oldData = null;
        for (int i = index; i < size - 1; i++) {
            oldData = (T) arr[i];
            arr[i] = arr[i + 1];
        }
        size--;
        return oldData;
    }

    /**
     * 改
     *
     * @param index 索引
     * @param data  值
     * @return
     */
    @Override
    public boolean set(int index, Object data) {
        checkElementPosition(index);
        arr[index] = data;
        return true;
    }

    /**
     * 得到数值
     *
     * @param index
     * @return
     */
    @Override
    public T getValue(int index) {
        checkElementPosition(index);
        return (T) arr[index];
    }

    /**
     * 数组长度
     *
     * @return
     */
    @Override
    public int size() {
        return size;
    }

    //索引不到元素？
    private void checkElementPosition(int index) {
        if (index < 0 || index >= size) {
            throw new RuntimeException("索引越界");
        }
    }

    //空间不够怎么办？
    private void container() {
        if (size >= arr.length) {
            Object[] temp = new Object[arr.length * 2];
            for (int i = 0; i < size; i++) {
                temp[i] = arr[i];
            }
            arr = temp;
        }
    }

    //索引不在范围怎么办？比如-1
    private void InsertElementPosition(int index) {
        if (index < 0 || index > size) {
            System.out.println("无法取到元素");
        }
    }
}
